package com.xsp.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xsp.commonutils.JwtUtils;
import com.xsp.eduservice.client.OrderClient;
import com.xsp.eduservice.entity.EduCourse;
import com.xsp.eduservice.entity.chapter.ChapterVo;
import com.xsp.eduservice.entity.frontvo.CourseFrontVo;
import com.xsp.eduservice.entity.frontvo.CourseWebVo;
import com.xsp.eduservice.service.EduChapterService;
import com.xsp.eduservice.service.EduCourseService;
import com.xsp.commonutils.R;
import com.xsp.ordervo.CourseWebVoOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/front/course")
public class CourseFrontController {
    @Autowired
    EduCourseService courseService;
    @Autowired
    EduChapterService chapterService;
    @Autowired
    OrderClient orderClient;

    //前台课程分页条件查询
    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page, @PathVariable long limit,
                                @RequestBody(required = false) CourseFrontVo courseFrontVo){
        Page<EduCourse> coursePage = new Page<EduCourse>(page,limit);
        Map<String,Object> map = courseService.getFrontCourseList(coursePage, courseFrontVo);
        return R.ok().data(map);
    }

    //根据id查询课程基本信息
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getById(@PathVariable String courseId, HttpServletRequest request){

        //查询课程信息和讲师信息
        CourseWebVo courseWebVo = courseService.getFrontCourseInfo(courseId);

        //查询当前课程的章节信息
        List<ChapterVo> chapterVoList = chapterService.getChapterVideoByCourseId(courseId);

        //根据课程id和用户id查询当前课程是否已支付
        //通过request拿到token解析拿到memberId
        //可以判断memberId是否为null来跳转登陆界面
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        boolean buyCourse = orderClient.isBuyCourse(courseId, memberIdByJwtToken);
        return R.ok().data("course", courseWebVo).data("chapterVoList", chapterVoList).data("isBuy",buyCourse);
    }

    //根据课程id查询课程信息
    @GetMapping("getCourseInfoOrder/{courseId}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String courseId) {
        CourseWebVo courseWebVo = courseService.getFrontCourseInfo(courseId);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(courseWebVo,courseWebVoOrder);
        return courseWebVoOrder;
    }

}
